﻿using System;
using System.Net;
using FluentValidation;
using Grundy.Common;
using Grundy.Message;
using Grundy.Message.Licensing;

namespace Grundy.Licensing.Server.Command
{
    public class ReassertCommand : ICommand
    {
        private readonly LicenseSessionStore _licenseSessionStore;
        private static ReassertRequestValidator _validator = new ReassertRequestValidator();

        public ReassertCommand(LicenseSessionStore licenseSessionStore)
        {
            _licenseSessionStore = licenseSessionStore;
        }

        public bool CanProcess(Request request)
        {
            return request is ReassertRequest;
        }

        public Response Process(Request request, EndPoint requestingEndPoint, Guid customerId, string customerName)
        {
            return Process((ReassertRequest)request, requestingEndPoint);
        }

        private Response Process(ReassertRequest request, EndPoint requestingEndPoint)
        {
            _validator.ValidateAndThrow(request);

            var lri = new LicenseRequestInformation { ClientSessionId = request.SessionId, ClientIdentifiers = request.Identifiers, FeatureIdentificationKey = request.FeatureIdentificationKey, EndPoint = requestingEndPoint };
            var sessionId = request.SessionId;
            var reasserted = _licenseSessionStore.Reassert(lri);

            if (!reasserted)
                sessionId = _licenseSessionStore.Checkout(lri);

            return new ReassertSucceededResponse { SessionId = sessionId, IsNewSession = !reasserted };
        }
    }
}